<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :sm="4" :xs="4">
        <div class="dept-tree">
          <el-card shadow="hover">
            <div class="tree-container">
              <el-input v-model="deptName" placeholder="请输入部门名称" prefix-icon="Search" clearable />
              <el-tree
                ref="deptTreeRef"
                class="mt-2"
                node-key="id"
                :data="deptOptions"
                :props="{ label: 'label', children: 'children' } as any"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                highlight-current
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :sm="20" :xs="20">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true">
                <!-- <el-form-item>
                  <el-badge :value="userSelectCount" :max="10" class="item">
                    <el-button type="primary" @click="openUserSelect">选择申请人</el-button>
                  </el-badge>
                </el-form-item> -->
                <el-form-item label="组织名称" label-width="100" prop="flowName">
                  <el-input v-model="queryParams.flowName" placeholder="请输入组织名称" @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['organ:archives:add']" type="primary" plain icon="Plus" @click="handleAdd()">新增组织 </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['organ:archives:move']" plain @click="handleToggleMove">转移</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['organ:archives:revoke']" type="warning" plain @click="handleRevoke">撤销</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['organ:archives:import']" plain>导入</el-button>
              </el-col>
              <el-col :span="1.5" style="display: flex; margin-left: auto">
                <el-input v-model="queryParams.flowName" placeholder="请输入组织名称" clearable @keyup.enter="handleQuery"> </el-input>
                <el-tooltip class="item" effect="dark" content="点击查询" placement="top">
                  <el-button style="margin: 0 12px" circle @click="handleQuery()">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </el-tooltip>
              </el-col>
              <right-toolbar v-model:show-search="showSearch" @query-table="handleQuery" style="margin-left: unset"></right-toolbar>
            </el-row>
          </template>
          <div ref="tableContainer" class="table-container">
            <el-table :height="tableHeight" v-loading="loading" border :data="taskList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
              <el-table-column :show-overflow-tooltip="true" prop="flowName" align="center" label="组织名称"></el-table-column>
              <el-table-column align="center" prop="flowCode" label="组织编码"></el-table-column>
              <el-table-column align="center" prop="categoryName" label="所属公司"></el-table-column>
              <el-table-column align="center" prop="nodeName" label="上级组织"></el-table-column>
              <el-table-column align="center" prop="nodeName" label="组织层级"></el-table-column>

              <el-table-column align="center" prop="createByName" label="主负责人"></el-table-column>
              <el-table-column align="center" label="创建人">
                <template #default="scope">
                  <template v-if="scope.row.assigneeNames">
                    <el-tag v-for="(name, index) in scope.row.assigneeNames.split(',')" :key="index" type="success">
                      {{ name }}
                    </el-tag>
                  </template>
                  <template v-else>
                    <el-tag type="success"> 无</el-tag>
                  </template>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="createTime" label="创建日期" width="160"></el-table-column>
              <el-table-column align="center" label="修改人">
                <template #default="scope">
                  <template v-if="scope.row.assigneeNames">
                    <el-tag v-for="(name, index) in scope.row.assigneeNames.split(',')" :key="index" type="success">
                      {{ name }}
                    </el-tag>
                  </template>
                  <template v-else>
                    <el-tag type="success"> 无</el-tag>
                  </template>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="createTime" label="修改日期" width="160"></el-table-column>

              <el-table-column fixed="right" label="操作" width="130">
                <template #default="scope">
                  <el-tooltip content="新建下级" placement="top">
                    <el-button v-hasPermi="['organ:archives:add']" link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
                  </el-tooltip>
                  <el-tooltip content="编辑" placement="top">
                    <el-button v-hasPermi="['organ:archives:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
                  </el-tooltip>
                  <el-tooltip content="撤销" placement="top">
                    <el-button
                      v-hasPermi="['organ:archives:revoke']"
                      link
                      type="primary"
                      icon="RefreshLeft"
                      @click="handleRevoke(scope.row)"
                    ></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :total="total"
              @pagination="handleQuery"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog ref="formDialogRef" v-model="dialog.visible" :title="dialog.title" append-to-body @close="closeDialog" class="p-6090-dialog">
      <el-form ref="userFormRef" :model="form" label-width="100px" label-suffix=":">
        <div style="font-size: 16px; font-weight: 700; padding-bottom: 15px">基本信息</div>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="上级组织" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入上级组织" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织层级" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入组织层级" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item required label="组织名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入组织名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="组织编码" prop="password">
              <el-input v-model="form.userName" placeholder="请输入组织编码" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item required label="显示顺序" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="所属公司" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="enabledDeptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' } as any"
                value-key="id"
                placeholder="请选择所属公司"
                check-strictly
                @change="handleDeptChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item required label="组织级别" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入组织级别" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="form.postIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == '1'"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="form.roleIds" filterable multiple placeholder="请选择">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == '1'"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <div style="font-size: 16px; font-weight: 700; padding-bottom: 15px">管理组信息</div>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="主负责人" prop="userName">
              <el-input v-model="form.userName" placeholder="请选择主负责人" maxlength="30" @focus="openUserSelect" />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="font-size: 16px; font-weight: 700; padding-bottom: 15px">公司信息</div>

        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="公司LOGO" prop="logo">
              <imageUpload v-model="form.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="法人" prop="password">
              <el-input v-model="form.userName" placeholder="请输入法人" maxlength="30" />
            </el-form-item>
            <el-form-item required label="公司电话" prop="password">
              <el-input v-model="form.userName" placeholder="请输入公司电话" maxlength="30" />
            </el-form-item>
            <el-form-item label="邮箱" prop="password">
              <el-input v-model="form.userName" placeholder="请输入邮箱" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item required label="公司全称">
              <el-input v-model="form.remark" placeholder="请输入公司全称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="地区信息">
              <el-input v-model="form.remark" placeholder="请输入地区信息"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item required label="公司地址">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 组织转移对话框 -->
    <el-dialog ref="MoveDialogRef" v-model="moveDialog.visible" :title="moveDialog.title" append-to-body class="p-6060-dialog">
      <div class="steps-container">
        <el-steps :active="stepActive" align-center finish-status="success">
          <el-step title="选择新的上级组织" />
          <el-step title="人员异动" />
          <el-step title="完成" />
        </el-steps>
      </div>
      <div v-show="stepActive == 0">
        <div style="font-size: 16px; font-weight: 700; padding-bottom: 15px">转移信息</div>
        <el-form ref="organFormRef" :model="form" label-width="120px" label-suffix=":">
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="待转移的组织" prop="deptId">
                <el-input v-model="moveForm.deptId" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="修改后的组织" prop="userId">
                <el-input v-model="moveForm.userId" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div v-show="stepActive == 1">
        <el-table border :data="moveList">
          <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
          <el-table-column label="姓名" align="center" prop="deptId" />
          <el-table-column label="工号" align="center" prop="userId" />
          <el-table-column label="原组织名称" align="center" prop="orderNum" />
          <el-table-column label="转移后组织名称" align="center" prop="testKey" />
          <el-table-column label="异动类型" align="center" prop="value" />
        </el-table>
      </div>
      <div v-show="stepActive == 2" style="text-align: center; margin-top: 50px">
        <el-icon color="#52c41a" :size="60"><SuccessFilled /></el-icon>
        <p style="font-size: 20px; margin-top: 20px">已完成!</p>
        <!-- <el-icon color="#f56c6c" :size="60"><WarningFilled /></el-icon>
        <p style="font-size: 20px; margin-top: 20px">异常!</p> -->
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="prevStep" v-if="stepActive == 1">上一步</el-button>
          <el-button type="primary" @click="nextStep" v-if="stepActive < 2">下一步</el-button>
          <el-button @click="cancelMove">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 申请人 -->
    <UserSelect ref="userSelectRef" :multiple="true" :data="selectUserIds" @confirm-call-back="userSelectCallBack"></UserSelect>
  </div>
</template>

<script setup lang="ts">
import api from '@/api/system/user';

import { pageByTaskWait } from '@/api/workflow/task';
import { TaskQuery, FlowTaskVO } from '@/api/workflow/task/types';
import workflowCommon from '@/api/workflow/workflowCommon';
import { RouterJumpVo } from '@/api/workflow/workflowCommon/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wf_business_status } = toRefs<any>(proxy?.useDict('wf_business_status'));
import UserSelect from './headerSelect.vue';
import { ref } from 'vue';
import { useTableHeight } from '@/hooks/useTableHeight';
import { UserForm, UserVO } from '@/api/system/user/types';
import { organVO } from '@/api/organization/archives/types';
import { DeptTreeVO, DeptVO } from '@/api/system/dept/types';
import { title } from 'process';

const userSelectRef = ref<InstanceType<typeof UserSelect>>();
//提交组件
const queryFormRef = ref<ElFormInstance>();
// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref<Array<any>>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(false);
// 总条数
const total = ref(0);
// 模型定义表格数据
const taskList = ref([]);
//申请人id
const selectUserIds = ref<Array<number | string>>([]);
//申请人选择数量
const userSelectCount = ref(0);
// 查询参数
const queryParams = ref<TaskQuery>({
  pageNum: 1,
  pageSize: 10,
  nodeName: undefined,
  flowName: undefined,
  flowCode: undefined,
  createByIds: []
});
// 部门树
const deptName = ref('');
const deptTreeRef = ref<ElTreeInstance>();
const deptOptions = ref<DeptTreeVO[]>([]);
const enabledDeptOptions = ref<DeptTreeVO[]>([]);
//新增弹窗
const formDialogRef = ref<ElDialogInstance>();
const userFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const form: UserForm = {
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: undefined,
  password: '',
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  status: '0',
  remark: '',
  postIds: [],
  roleIds: []
};
//自适应表格高度
const tableContainer = ref(null);
const { tableHeight } = useTableHeight({
  containerRef: tableContainer,
  offset: 82
});
const nextLoading = ref(false);
//转移弹窗
const MoveDialogRef = ref<ElDialogInstance>();
const organFormRef = ref<ElFormInstance>();
const moveDialog = reactive<DialogOption>({
  visible: false,
  title: '组织转移'
});
const moveForm: UserForm = {
  userId: undefined,
  deptId: undefined,
  userName: '',
  password: '',
  status: '',
  postIds: [],
  roleIds: []
};
const stepActive = ref(0);
const moveList = ref([]);

onMounted(() => {
  getDeptTree(); // 初始化部门数据
  getWaitingList();
});
/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watchEffect(
  () => {
    deptTreeRef.value?.filter(deptName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);
/** 搜索按钮操作 */
const handleQuery = () => {
  getWaitingList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  queryParams.value.createByIds = [];
  userSelectCount.value = 0;
  selectUserIds.value = [];
  deptTreeRef.value?.setCurrentKey(undefined);

  handleQuery();
};
// 多选框选中数据
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};
//分页
const getWaitingList = () => {
  loading.value = true;
  pageByTaskWait(queryParams.value).then((resp) => {
    taskList.value = resp.rows;
    total.value = resp.total;
    loading.value = false;
  });
};

//打开申请人选择
const openUserSelect = () => {
  userSelectRef.value.open();
};
//确认选择申请人
const userSelectCallBack = (data: UserVO[]) => {
  userSelectCount.value = 0;
  if (data && data.length > 0) {
    userSelectCount.value = data.length;
    selectUserIds.value = data.map((item) => item.userId);
    // queryParams.value.createByIds = selectUserIds.value;
  }
};
//新增组织
const handleAdd = async () => {
  reset();
  const { data } = await api.getUser();
  dialog.visible = true;
  dialog.title = '组织档案详情';
  // postOptions.value = data.posts;
  // roleOptions.value = data.roles;
  // form.value.password = initPassword.value.toString();
};
//转移
const handleToggleMove = () => {
  moveDialog.visible = true;
};
//撤销
const handleRevoke = async (row?: organVO) => {
  const name = row?.flowName;
  const content = '无法撤销！' + name + '组织或其下级组织包含在职人员，请先前往人员异动处理！';
  await ElMessageBox.confirm(content, '撤销组织', {
    confirmButtonText: '去处理',
    cancelButtonText: '关闭',
    type: 'warning'
  });
};
/** 节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.deptId = data.id;
  handleQuery();
};
/** 查询部门下拉树结构 */
const getDeptTree = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
  enabledDeptOptions.value = filterDisabledDept(res.data);
};
/** 过滤禁用的部门 */
const filterDisabledDept = (deptList: DeptTreeVO[]) => {
  return deptList.filter((dept) => {
    if (dept.disabled) {
      return false;
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children);
    }
    return true;
  });
};
/** 重置操作表单 */
const reset = () => {
  // form.value = { ...from };
  userFormRef.value?.resetFields();
};
/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
  reset();
};
/** 修改按钮操作 */
// const handleUpdate = async (row?: UserForm) => {
//   reset();
//   const userId = row?.userId || ids.value[0];
//   const { data } = await api.getUser(userId);
//   dialog.visible = true;
//   dialog.title = '编辑用户信息';
//   Object.assign(form.value, data.user);
//   postOptions.value = data.posts;
//   roleOptions.value = data.roles;
//   form.value.postIds = data.postIds;
//   form.value.roleIds = data.roleIds;
//   form.value.password = '';
// };

/** 提交按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.userId ? await api.updateUser(form.value) : await api.addUser(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getWaitingList();
    }
  });
};
/**
 * 关闭用户弹窗
 */
const closeDialog = () => {
  dialog.visible = false;
  resetForm();
};

/**
 * 重置表单
 */
const resetForm = () => {
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();

  // form.value.id = undefined;
  // form.value.status = '1';
};
const prevStep = () => {
  stepActive.value--;
  console.log('prevStep', stepActive.value);
};
const nextStep = () => {
  stepActive.value++;
  console.log('nextStep', stepActive.value);
};
const cancelMove = () => {
  moveDialog.visible = false;
  stepActive.value = 0;
};
</script>
<style lang="scss" scoped>
.steps-container {
  padding: 20px 0;
  :deep(.is-success) {
    color: #409eff;
    border-color: #409eff;
    .el-step__line {
      background-color: #409eff;
    }
    .el-step__icon {
      background: #409eff;
      color: #fff;
    }
  }
  :deep(.is-process) {
    color: #409eff;
    border-color: #409eff;
  }
}
:deep(.dept-tree) {
  height: 100%;
  .el-card {
    height: 100%;
  }
  .el-card__body {
    height: 100%;
  }
  .tree-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    // overflow: visible;

    .el-tree {
      flex: 1;
      overflow-y: auto; // 关键：添加垂直滚动条
      .el-tree-node > .el-tree-node__children {
        overflow: visible !important;
      }
    }
  }
  .table-container {
    height: 100%;
  }
}
</style>
